{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 1.使用 Xavier 初始化。\n",
    "- 2.每次只取一个batch，减少内存占用\n",
    "- 3.字符embedding\n",
    "\n",
    "实际参数是 1,2,3,4,5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting ...\n",
      "Prepared, costed time 0.0135429 s.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt \n",
    "from gensim.models import KeyedVectors\n",
    "import pickle\n",
    "import os\n",
    "import sys\n",
    "import shutil\n",
    "import time\n",
    "\n",
    "\n",
    "time0 = time.time()\n",
    "print('Starting ...')\n",
    "model_name = 'ch3-2-cnn-256-23457'                    # 模型名称\n",
    "W_embedding = np.load('/home1/huangyongye/mygithub/zhihu/data/ch_W_embedding.npy').astype(np.float32)            # 导入预训练好的词向量\n",
    "model_path = '../ckpt/' + model_name + '/'                  # 模型保存位置\n",
    "summary_path = '../summary/' + model_name + '/'             # summary 位置\n",
    "result_path = '../result/' + model_name + '.csv'            # result.csv 位置\n",
    "scores_path = '../scores/' + model_name + '.npy'            # scores.npy 位置\n",
    "local_scores_path = '../local_scores/' + model_name + '.npy'\n",
    "\n",
    "\n",
    "if not os.path.exists(model_path):\n",
    "    os.makedirs(model_path)         \n",
    "model_path = model_path + 'model.ckpt'\n",
    "if os.path.exists(summary_path):   # 删除原来的 summary 文件，避免重合\n",
    "    print('removed the existing summary files.')\n",
    "    shutil.rmtree(summary_path)\n",
    "os.makedirs(summary_path)          # 然后再次创建\n",
    "    \n",
    "# ##################### config ######################\n",
    "n_step1 = max_len1 = 52                   # title句子长度\n",
    "n_step2 = max_len2 = 300                   # content 长度\n",
    "input_size = embedding_size = 256       # 字向量长度\n",
    "n_class = 1999                          # 类别总数\n",
    "filter_sizes = [1,2,3,4,5]                  # 卷积核大小\n",
    "n_filter = 256                          # 每种卷积核的个数\n",
    "fc_hidden_size = 1024                   # fc 层节点数\n",
    "n_filter_total = n_filter * len(filter_sizes)\n",
    "valid_num = 100000\n",
    "seed_num = 13\n",
    "tr_batch_size = 128\n",
    "te_batch_size = 128\n",
    "print('Prepared, costed time %g s.' % (time.time() - time0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Building model ...\n",
      "Finished creating the TextCNN model.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "config = tf.ConfigProto()\n",
    "config.gpu_options.allow_growth = True\n",
    "sess = tf.Session(config=config)\n",
    "from tensorflow.contrib import rnn\n",
    "import tensorflow.contrib.layers as layers\n",
    "\n",
    "'''\n",
    "双端 GRU，知乎问题多标签分类。\n",
    "'''\n",
    "print('Building model ...')\n",
    "keep_prob = tf.placeholder(tf.float32, [])\n",
    "batch_size = tf.placeholder(tf.int32, [])  # 注意类型必须为 tf.int32\n",
    "tst = tf.placeholder(tf.bool)\n",
    "n_updates = tf.placeholder(tf.int32)      # training iteration,传入 bn 层\n",
    "update_emas = list()                       # BN 层中所有的更新操作\n",
    "\n",
    "\n",
    "def weight_variable(shape, name, initializer=None):\n",
    "    \"\"\"Create a weight variable with appropriate initialization.\"\"\"\n",
    "    initial = tf.truncated_normal(shape, stddev=0.1)\n",
    "    return tf.get_variable(name=name, initializer=initial, dtype=tf.float32)\n",
    "\n",
    "def bias_variable(shape, name):\n",
    "    \"\"\"Create a bias variable with appropriate initialization.\"\"\"\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.get_variable(name=name, initializer=initial, dtype=tf.float32)\n",
    "\n",
    "def batchnorm(Ylogits, is_test, num_updates, offset, convolutional=False):\n",
    "    \"\"\"batchnormalization.\n",
    "    Args:\n",
    "        Ylogits: 1D向量或者是3D的卷积结果。\n",
    "        num_updates: 迭代的global_step\n",
    "        offset：表示beta，全局均值；在 RELU 激活中一般初始化为 0.1。\n",
    "        scale：表示lambda，全局方差；在 sigmoid 激活中需要，这 RELU 激活中作用不大。\n",
    "        m: 表示batch均值；v:表示batch方差。\n",
    "        bnepsilon：一个很小的浮点数，防止除以 0.\n",
    "    Returns:\n",
    "        Ybn: 和 Ylogits 的维度一样，就是经过 Batch Normalization 处理的结果。\n",
    "        update_moving_everages：更新mean和variance，主要是给最后的 test 使用。\n",
    "    \"\"\"\n",
    "    exp_moving_avg = tf.train.ExponentialMovingAverage(0.999, num_updates) # adding the iteration prevents from averaging across non-existing iterations\n",
    "    bnepsilon = 1e-5\n",
    "    if convolutional:\n",
    "        mean, variance = tf.nn.moments(Ylogits, [0, 1, 2])\n",
    "    else:\n",
    "        mean, variance = tf.nn.moments(Ylogits, [0])\n",
    "    update_moving_everages = exp_moving_avg.apply([mean, variance])\n",
    "    m = tf.cond(is_test, lambda: exp_moving_avg.average(mean), lambda: mean)\n",
    "    v = tf.cond(is_test, lambda: exp_moving_avg.average(variance), lambda: variance)\n",
    "    Ybn = tf.nn.batch_normalization(Ylogits, m, v, offset, None, bnepsilon)\n",
    "    return Ybn, update_moving_everages\n",
    "\n",
    "\n",
    "with tf.name_scope('Inputs'):\n",
    "    X1_inputs = tf.placeholder(tf.int64, [None, n_step1], name='X1_input')\n",
    "    X2_inputs = tf.placeholder(tf.int64, [None, n_step2], name='X2_input')\n",
    "    y_inputs = tf.placeholder(tf.float32, [None, n_class], name='y_input')    \n",
    "\n",
    "with tf.device('/gpu:0'):\n",
    "    with tf.variable_scope('embedding') as vs:\n",
    "        embedding = tf.get_variable(name=\"W_embedding\", shape=W_embedding.shape, \n",
    "                            initializer=tf.constant_initializer(W_embedding), trainable=True)   # fine-tune\n",
    "\n",
    "def textcnn(X_inputs, n_step):\n",
    "    \"\"\"build the TextCNN network. Return the h_drop\"\"\"\n",
    "    # X_inputs.shape = [batchsize, n_step]  ->  inputs.shape = [batchsize, n_step, embedding_size]\n",
    "    inputs = tf.nn.embedding_lookup(embedding, X_inputs)  \n",
    "    inputs = tf.expand_dims(inputs, -1)\n",
    "    pooled_outputs = list()\n",
    "    for i, filter_size in enumerate(filter_sizes):\n",
    "        with tf.variable_scope(\"conv-maxpool-%s\" % filter_size):\n",
    "            # Convolution Layer\n",
    "            filter_shape = [filter_size, embedding_size, 1, n_filter]\n",
    "            W_filter = weight_variable(shape=filter_shape, name='W_filter')\n",
    "            beta = bias_variable(shape=[n_filter], name='beta_filter')\n",
    "            tf.summary.histogram('beta_filter', beta)\n",
    "            conv = tf.nn.conv2d(inputs, W_filter, strides=[1, 1, 1, 1], padding=\"VALID\", name=\"conv\")\n",
    "            conv_bn, update_ema = batchnorm(conv, tst, n_updates, beta, convolutional=True)    # 在激活层前面加 BN\n",
    "            # Apply nonlinearity, batch norm scaling is not useful with relus\n",
    "            # batch norm offsets are used instead of biases,使用 BN 层的 offset，不要 biases\n",
    "            h = tf.nn.relu(conv_bn, name=\"filter_relu\")\n",
    "            # Maxpooling over the outputs\n",
    "            pooled = tf.nn.max_pool(h,ksize=[1, n_step - filter_size + 1, 1, 1],\n",
    "                strides=[1, 1, 1, 1],padding='VALID',name=\"pool\")\n",
    "            pooled_outputs.append(pooled)\n",
    "            update_emas.append(update_ema)\n",
    "    h_pool = tf.concat(pooled_outputs, 3)\n",
    "    h_pool_flat = tf.reshape(h_pool, [-1, n_filter_total]) \n",
    "    return h_pool_flat    # shape = [-1, n_filter_total]\n",
    "    \n",
    "    \n",
    "with tf.variable_scope('cnn-title'):\n",
    "    output_title = textcnn(X1_inputs, n_step1)\n",
    "with tf.variable_scope('cnn-content'):\n",
    "    output_content = textcnn(X2_inputs, n_step2)\n",
    "with tf.variable_scope('fc-bn-layer'):\n",
    "    output = tf.concat([output_title, output_content], axis=1)\n",
    "    W_fc = weight_variable([n_filter_total*2, fc_hidden_size], name='Weight_fc')\n",
    "    tf.summary.histogram('W_fc', W_fc)\n",
    "    h_fc = tf.matmul(output, W_fc, name='h_fc')\n",
    "    beta_fc = bias_variable([fc_hidden_size], name=\"beta_fc\")\n",
    "    tf.summary.histogram('beta_fc', beta_fc)\n",
    "    fc_bn, update_ema_fc = batchnorm(h_fc, tst, n_updates, beta_fc, convolutional=False)\n",
    "    update_emas.append(update_ema_fc)\n",
    "    fc_bn_relu = tf.nn.relu(fc_bn, name=\"relu\")\n",
    "#     fc_bn_drop = tf.nn.dropout(fc_bn_relu, keep_prob, name=\"fc_dropout\")  # 不加 dropout\n",
    "\n",
    "with tf.variable_scope('out_layer'):\n",
    "    W_out = weight_variable(shape=[fc_hidden_size, n_class], name='Weight_out')\n",
    "    tf.summary.histogram('Weight_out', W_out)\n",
    "    b_out = bias_variable([n_class], name='bias_out') \n",
    "    tf.summary.histogram('bias_out', b_out)\n",
    "    y_pred = tf.nn.xw_plus_b(fc_bn_relu, W_out, b_out, name='y_pred')  #每个类别的分数 scores\n",
    "    \n",
    "with tf.name_scope('cost'):\n",
    "    cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_pred, labels=y_inputs))\n",
    "    tf.summary.scalar('cost', cost)\n",
    "\n",
    "#  ------------- 优化器设置 ---------------------\n",
    "global_step = tf.Variable(0, trainable=False, name='Global_Step')\n",
    "update_global_step = tf.assign(global_step, global_step+1)\n",
    "starter_learning_rate = 1.0e-3\n",
    "decay_step = 10000\n",
    "# decay_step = 25  # 测试用\n",
    "decay = 0.65 \n",
    "learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step, decay_step, decay, staircase=True)\n",
    "with tf.variable_scope('AdamOptimizer1'):\n",
    "    tvars1 = tf.trainable_variables()\n",
    "    grads1 = tf.gradients(cost, tvars1)\n",
    "    optimizer1 = tf.train.AdamOptimizer(learning_rate)\n",
    "    train_op1 = optimizer1.apply_gradients(zip(grads1, tvars1),\n",
    "        global_step=global_step)\n",
    "\n",
    "update_op = tf.group(*update_emas)   # 更新 BN 参数    \n",
    "\n",
    "# summary\n",
    "merged = tf.summary.merge_all() # summary\n",
    "train_writer = tf.summary.FileWriter(summary_path + 'train', sess.graph)\n",
    "test_writer = tf.summary.FileWriter(summary_path + 'test')\n",
    "print 'Finished creating the TextCNN model.'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "n_tr_batch=22656\n",
      "n_va_batches=782\n",
      "Every thing prepared!\n"
     ]
    }
   ],
   "source": [
    "sys.path.append('..')\n",
    "from data_helpers import BatchGenerator\n",
    "from data_helpers import to_categorical\n",
    "from evaluator import score_eval\n",
    "\n",
    "\n",
    "data_train_path = '/home2/huangyongye/zhihu/ch-data/data_train/'\n",
    "data_valid_path = '/home2/huangyongye/zhihu/ch-data/data_valid/'\n",
    "tr_batches = os.listdir(data_train_path)   # batch 文件名列表\n",
    "va_batches = os.listdir(data_valid_path)\n",
    "n_tr_batches = len(tr_batches)\n",
    "n_va_batches = len(va_batches)\n",
    "\n",
    "# n_tr_batches = 2000  # 测试用\n",
    "# n_va_batches = 100\n",
    "\n",
    "print('n_tr_batch=%d' % n_tr_batches)\n",
    "print('n_va_batches=%d' % n_va_batches)\n",
    "\n",
    "\n",
    "def get_batch(data_path, batch_id, title_len=n_step1):\n",
    "    \"\"\"get a batch from data_path\"\"\"\n",
    "    new_batch = np.load(data_path + str(batch_id) + '.npz')\n",
    "    X_batch = new_batch['X']\n",
    "    y_batch = new_batch['y']\n",
    "    X1_batch = X_batch[:, :title_len]\n",
    "    X2_batch = X_batch[:, title_len:]\n",
    "    return [X1_batch, X2_batch, y_batch]\n",
    "\n",
    "\n",
    "def valid_epoch(data_path=data_valid_path):\n",
    "    \"\"\"Test on the valid data.\"\"\"\n",
    "    _costs = 0.0\n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    marked_labels_list = list()   # 真实标签\n",
    "    _global_step = sess.run(global_step)\n",
    "    for i in xrange(n_va_batches):\n",
    "        [X1_batch, X2_batch, y_batch] = get_batch(data_path, i)\n",
    "        marked_labels_list.extend(y_batch)\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        fetches = [merged, cost, y_pred]  \n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch,  y_inputs:y_batch, \n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:_global_step}\n",
    "        summary, _cost, predict_labels = sess.run(fetches, feed_dict)\n",
    "        _costs += _cost\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "    precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "    mean_cost = _costs / n_va_batches\n",
    "    return mean_cost, precision, recall, f1\n",
    "\n",
    "print('Every thing prepared!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  模型训练"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之前的训练速度 9334.15 s/epoch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tr_batch_num=22656\n"
     ]
    }
   ],
   "source": [
    "# 测试\n",
    "# valid_step = 1000        # 每 valid_step 就进行一次 valid 运算\n",
    "# max_max_epoch = 2       # 最多迭代的次数\n",
    "\n",
    "\n",
    "# 正式\n",
    "valid_step = 8000        # 每 valid_step 就进行一次 valid 运算\n",
    "max_max_epoch = 7       # 最多迭代的次数\n",
    "\n",
    "print('tr_batch_num=%d' % n_tr_batches)\n",
    "saver = tf.train.Saver(max_to_keep=5)           # 最多保存的模型数量\n",
    "sess.run(tf.global_variables_initializer())\n",
    "last_f1 = 0.39\n",
    "model_num = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EPOCH 1, lr= 0.001\n",
      "Global_step=7999: valid cost=0.00819452; p=0.932718, r=0.387906, f1=0.273967, time=3967.66 s\n",
      "Global_step=15999: valid cost=0.00616893; p=1.14399, r=0.472713, f1=0.334495, time=3963.87 s\n",
      "EPOCH 2, lr= 0.0004225\n",
      "Global_step=23999: valid cost=0.00521483; p=1.26176, r=0.518082, f1=0.367277, time=3763.93 s\n",
      "Global_step=31999: valid cost=0.00471285; p=1.30201, r=0.533594, f1=0.378482, time=3703.12 s\n",
      "Global_step=39999: valid cost=0.00491511; p=1.30592, r=0.535205, f1=0.379624, time=3713.12 s\n",
      "EPOCH 3, lr= 0.000178506\n",
      "Global_step=47999: valid cost=0.00438203; p=1.34389, r=0.549708, f1=0.390129, time=3677.21 s\n",
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-1')\n",
      "Global_step=55999: valid cost=0.0041409; p=1.3552, r=0.554125, f1=0.393307, time=3595.93 s\n",
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-2')\n",
      "Global_step=63999: valid cost=0.00408978; p=1.36658, r=0.558264, f1=0.39635, time=3944.55 s\n",
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-3')\n",
      "EPOCH 4, lr= 7.54189e-05\n",
      "Global_step=71999: valid cost=0.00405638; p=1.37023, r=0.55985, f1=0.397457, time=3710.05 s\n",
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-4')\n",
      "Global_step=79999: valid cost=0.00405817; p=1.3693, r=0.55876, f1=0.396829, time=4098.97 s\n",
      "Global_step=87999: valid cost=0.00405039; p=1.37089, r=0.559846, f1=0.39751, time=3775.37 s\n",
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-5')\n",
      "EPOCH 5, lr= 2.07119e-05\n",
      "Global_step=95999: valid cost=0.00404395; p=1.37204, r=0.560158, f1=0.397764, time=3966.59 s\n",
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-6')\n",
      "Global_step=103999: valid cost=0.00404203; p=1.3719, r=0.560038, f1=0.397692, time=3905.6 s\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-5-786a5a0e83cd>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     35\u001b[0m                          batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:_global_step}\n\u001b[1;32m     36\u001b[0m             \u001b[0mfetches\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mmerged\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcost\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 37\u001b[0;31m             \u001b[0msummary\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_cost\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msess\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfetches\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfeed_dict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     38\u001b[0m             \u001b[0mtest_writer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_summary\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msummary\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_global_step\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     39\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36mrun\u001b[0;34m(self, fetches, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m    787\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    788\u001b[0m       result = self._run(None, fetches, feed_dict, options_ptr,\n\u001b[0;32m--> 789\u001b[0;31m                          run_metadata_ptr)\n\u001b[0m\u001b[1;32m    790\u001b[0m       \u001b[0;32mif\u001b[0m \u001b[0mrun_metadata\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    791\u001b[0m         \u001b[0mproto_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtf_session\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mTF_GetBuffer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrun_metadata_ptr\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_run\u001b[0;34m(self, handle, fetches, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m    995\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mfinal_fetches\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mfinal_targets\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    996\u001b[0m       results = self._do_run(handle, final_targets, final_fetches,\n\u001b[0;32m--> 997\u001b[0;31m                              feed_dict_string, options, run_metadata)\n\u001b[0m\u001b[1;32m    998\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    999\u001b[0m       \u001b[0mresults\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_do_run\u001b[0;34m(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m   1130\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mhandle\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1131\u001b[0m       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,\n\u001b[0;32m-> 1132\u001b[0;31m                            target_list, options, run_metadata)\n\u001b[0m\u001b[1;32m   1133\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1134\u001b[0m       return self._do_call(_prun_fn, self._session, handle, feed_dict,\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_do_call\u001b[0;34m(self, fn, *args)\u001b[0m\n\u001b[1;32m   1137\u001b[0m   \u001b[0;32mdef\u001b[0m \u001b[0m_do_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1138\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1139\u001b[0;31m       \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1140\u001b[0m     \u001b[0;32mexcept\u001b[0m \u001b[0merrors\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mOpError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1141\u001b[0m       \u001b[0mmessage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcompat\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mas_text\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmessage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_run_fn\u001b[0;34m(session, feed_dict, fetch_list, target_list, options, run_metadata)\u001b[0m\n\u001b[1;32m   1119\u001b[0m         return tf_session.TF_Run(session, options,\n\u001b[1;32m   1120\u001b[0m                                  \u001b[0mfeed_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfetch_list\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtarget_list\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1121\u001b[0;31m                                  status, run_metadata)\n\u001b[0m\u001b[1;32m   1122\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1123\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0m_prun_fn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msession\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhandle\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfeed_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfetch_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "time0 = time.time()\n",
    "train_op = train_op1 \n",
    "\n",
    "for epoch in xrange(max_max_epoch):\n",
    "    batch_indexs = np.random.permutation(n_tr_batches)  # shuffle the training data\n",
    "    print 'EPOCH %d, lr= %g' % (epoch+1, sess.run(learning_rate))    \n",
    "    for batch in xrange(n_tr_batches): \n",
    "        _global_step = sess.run(global_step)\n",
    "        if (_global_step+1) % valid_step == 0:    # 进行 valid 计算\n",
    "            valid_cost, precision, recall, f1 = valid_epoch()\n",
    "            print('Global_step=%d: valid cost=%g; p=%g, r=%g, f1=%g, time=%g s' % (\n",
    "                    _global_step, valid_cost, precision, recall, f1, time.time()-time0))\n",
    "            time0 = time.time()\n",
    "            if (f1 > last_f1):\n",
    "                last_f1 = f1\n",
    "                model_num += 1\n",
    "                save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "                print('the save path is ', save_path) \n",
    "                \n",
    "        batch_id = batch_indexs[batch]\n",
    "        [X1_batch, X2_batch, y_batch] = get_batch(data_train_path, batch_id, n_step1)\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        fetches = [merged, cost, train_op, update_op]\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, y_inputs:y_batch, batch_size:_batch_size, \n",
    "                     keep_prob:0.5, tst:False, n_updates:_global_step}\n",
    "        summary, _cost, _, _ = sess.run(fetches, feed_dict) # the cost is the mean cost of one batch\n",
    "        if _global_step % 200:\n",
    "            train_writer.add_summary(summary, _global_step)\n",
    "            batch_id = np.random.randint(0, n_va_batches)   # 随机选一个验证batch\n",
    "            [X1_batch, X2_batch, y_batch] = get_batch(data_valid_path, batch_id, n_step1)\n",
    "            y_batch = to_categorical(y_batch)\n",
    "            _batch_size = len(y_batch)\n",
    "            feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch,  y_inputs:y_batch,\n",
    "                         batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:_global_step}\n",
    "            fetches = [merged, cost]\n",
    "            summary, _cost = sess.run(fetches, feed_dict)\n",
    "            test_writer.add_summary(summary, _global_step)\n",
    "\n",
    "valid_cost, precision, recall, f1 = valid_epoch()  # # 每个 epoch 进行一次验证 valid\n",
    "print('Global_step=%d;  valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (\n",
    "    _global_step, valid_cost, precision, recall, f1, time.time()-time0) )\n",
    "if (f1 > last_f1):\n",
    "    model_num += 1\n",
    "    save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "    print('the save path is ', save_path) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('the save path is ', '../ckpt/ch3-2-cnn-256-23457/model.ckpt-1')\n"
     ]
    }
   ],
   "source": [
    "model_num += 1\n",
    "save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "print('the save path is ', save_path) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "继续迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Begin updating embedding.\n",
      "EPOCH 2, lr= 0.000580319\n",
      "Global_step=4999: valid cost=0.00961977; p=0.929033, r=0.39252, f1=0.275936, time=387.53 s\n",
      "Global_step=5999: valid cost=0.0095899; p=0.941763, r=0.39592, f1=0.278738, time=386.557 s\n",
      "Global_step=5999;  valid cost=0.00958995; p=0.942982, r=0.396253, f1=0.27901; speed=20.236 s/epoch\n"
     ]
    }
   ],
   "source": [
    "time0 = time.time()\n",
    "\n",
    "train_op = train_op1\n",
    "if model_num == 0:\n",
    "    model_num += 1\n",
    "    save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "    print('the save path is ', save_path)\n",
    "print('Begin updating embedding.')\n",
    "\n",
    "for epoch in xrange(1, max_max_epoch):\n",
    "    batch_indexs = np.random.permutation(n_tr_batches)  # shuffle the training data\n",
    "    print 'EPOCH %d, lr= %g' % (epoch+1, sess.run(learning_rate))    \n",
    "    for batch in xrange(n_tr_batches): \n",
    "        _global_step = sess.run(global_step)\n",
    "        if (_global_step+1) % valid_step == 0:    # 进行 valid 计算\n",
    "            valid_cost, precision, recall, f1 = valid_epoch()\n",
    "            print('Global_step=%d: valid cost=%g; p=%g, r=%g, f1=%g, time=%g s' % (\n",
    "                    _global_step, valid_cost, precision, recall, f1, time.time()-time0))\n",
    "            time0 = time.time()\n",
    "            if (f1 > last_f1):\n",
    "                last_f1 = f1\n",
    "                model_num += 1\n",
    "                save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "                print('the save path is ', save_path) \n",
    "                \n",
    "        batch_id = batch_indexs[batch]\n",
    "        [X1_batch, X2_batch, y_batch] = get_batch(data_train_path, batch_id, n_step1)\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        fetches = [merged, cost, train_op, update_op]\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, y_inputs:y_batch, batch_size:_batch_size, \n",
    "                     keep_prob:0.5, tst:False, n_updates:_global_step}\n",
    "        summary, _cost, _, _ = sess.run(fetches, feed_dict) # the cost is the mean cost of one batch\n",
    "        if _global_step % 100:\n",
    "            train_writer.add_summary(summary, _global_step)\n",
    "            batch_id = np.random.randint(0, n_va_batches)   # 随机选一个验证batch\n",
    "            [X1_batch, X2_batch, y_batch] = get_batch(data_valid_path, batch_id, n_step1)\n",
    "            y_batch = to_categorical(y_batch)\n",
    "            _batch_size = len(y_batch)\n",
    "            feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch,  y_inputs:y_batch,\n",
    "                         batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:_global_step}\n",
    "            fetches = [merged, cost]\n",
    "            summary, _cost = sess.run(fetches, feed_dict)\n",
    "            test_writer.add_summary(summary, _global_step)\n",
    "\n",
    "valid_cost, precision, recall, f1 = valid_epoch()  # # 每个 epoch 进行一次验证 valid\n",
    "print('Global_step=%d;  valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (\n",
    "    _global_step, valid_cost, precision, recall, f1, time.time()-time0) )\n",
    "if (f1 > last_f1):\n",
    "    model_num += 1\n",
    "    save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "    print('the save path is ', save_path) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "valid cost=0.00400637; p=1.42095, r=0.579586, f1=0.411671; speed=7431.4 s/epoch\n",
      "the save path is ../ckpt/textcnn-fc-drop-title-content-256-23457/model.ckpt-6 \n"
     ]
    }
   ],
   "source": [
    "valid_cost, precision, recall, f1 = valid_epoch()  # #每个 epoch 结束后进行一次整体 valid\n",
    "print('valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (valid_cost, precision, recall, f1, time.time()-time0) )\n",
    "save_path = saver.save(sess, model_path, global_step=(epoch+1))\n",
    "print('the save path is %s ' % save_path) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Bi-LSTM 模型<br/>\n",
    "**batch_size=256，迭代12个epoch，基本收敛。结果： 验证集 f1=0.38618； 提交结果 0.3873186**\n",
    "- Bi-GRU 模型<br/>\n",
    "**batch_size=256，迭代15个epoch。大概在 13 个 epoch 就收敛了。结果： 验证集 f1=0.390534； 提交结果 0.39198**\n",
    "- attention-Bi-GRU 模型<br/>\n",
    "**batch_size=256，迭代18个epoch。在16个epoch收敛。结果：验证集 f1=f1=0.391734 ；提交结果 0.39310**\n",
    "\n",
    "\n",
    "- textcnn-256 lr=1e-3, decay=0.65, dropout=0.5, 迭代6次基本收敛， f1=0.388\n",
    "- textcnn-256-bn lr=1.5E-3，decay=0.65, dropout=0.5, 6次基本收敛，8次好一点， f1=0.389\n",
    "- textcnn-fc-drop 迭代 4.5 个epoch 收敛。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 本地测试\n",
    "使用 seed13 的前 10万条数据."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 保存 本地测试的标注数据\n",
    "np.save('../data/marked_labels_list.npy', marked_labels_list)\n",
    "local_scores_path = '../local_scores/' + model_name + '.npy'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from ../ckpt/ch3-2-cnn-256-23457/model.ckpt-6\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|          | 1/782 [00:00<01:29,  8.69it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Finished loading model.\n",
      "local predicting ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 782/782 [00:58<00:00, 13.33it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "local valid p=1.37204, r=0.560158, f1=0.397764; speed=59.1824 s/epoch\n",
      "Writed the scores into ../local_scores/ch3-2-cnn-256-23457.npy, time 59.7809 s\n"
     ]
    }
   ],
   "source": [
    "# 导入保存好的模型\n",
    "saver = tf.train.Saver()\n",
    "best_model_path = model_path + '-' + str(6)  # 导入最优模型\n",
    "saver.restore(sess, best_model_path)\n",
    "print('Finished loading model.')\n",
    "local_scores_path = '../local_scores/' + model_name + '.npy'\n",
    "\n",
    "# 导入测试数据\n",
    "def local_predict(scores_path=local_scores_path, data_path=data_valid_path):\n",
    "    \"\"\"预测  valid 结果，并保存预测概率 到  scores.csv 文件中。\"\"\"\n",
    "    from tqdm import tqdm\n",
    "    print('local predicting ...')\n",
    "    time0 = time.time()\n",
    "    fetches = [y_pred]   \n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    marked_labels_list = list()   # 真实标签\n",
    "    predict_scores = list()\n",
    "    _global_step = sess.run(global_step)\n",
    "    for i in tqdm(xrange(n_va_batches)):\n",
    "        [X1_batch, X2_batch, y_batch] = get_batch(data_path, i)\n",
    "        marked_labels_list.extend(y_batch)\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch,  y_inputs:y_batch, \n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:_global_step}\n",
    "        predict_labels = sess.run(fetches, feed_dict)[0]\n",
    "        predict_scores.append(predict_labels)\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_scores = np.asarray(predict_scores)\n",
    "    predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "    precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "    print('local valid p=%g, r=%g, f1=%g; speed=%g s/epoch' % ( precision, recall, f1, time.time()-time0) )\n",
    "    np.save(local_scores_path, predict_scores)\n",
    "    print('Writed the scores into %s, time %g s' % (local_scores_path, time.time()-time0))\n",
    "    \n",
    "local_predict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 对测试数据进行预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 导入保存好的模型\n",
    "# saver = tf.train.Saver()\n",
    "# best_model_path = model_path + '-' + str(8)  # 导入最优模型\n",
    "# saver.restore(sess, best_model_path)\n",
    "# print('Finished loading model.')\n",
    "\n",
    "# 导入测试数据\n",
    "def predict():\n",
    "    \"\"\"预测测试集结果，并保存到  result.csv 文件中。\"\"\"\n",
    "    from tqdm import tqdm\n",
    "    \n",
    "    data_path = '../ch-data/data_test/'\n",
    "    n_te_batches = len(os.listdir(data_path))\n",
    "    fetches = [y_pred]   \n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    predict_scores = list()\n",
    "    _global_step = sess.run(global_step)\n",
    "    for i in tqdm(xrange(n_te_batches)):\n",
    "        X_batch = np.load(data_path + str(i) + '.npy')\n",
    "        X1_batch = X_batch[:, :n_step1]\n",
    "        X2_batch = X_batch[:, n_step1:]\n",
    "        _batch_size = len(X_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch,\n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:_global_step}\n",
    "        predict_labels = sess.run(fetches, feed_dict)[0]\n",
    "        predict_scores.append(predict_labels)\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_scores = np.asarray(predict_scores)\n",
    "    return predict_labels_list, np.vstack(predict_scores)\n",
    "\n",
    "def write_result(predict_labels_list, result_path):\n",
    "    \"\"\"把结果写到 result.csv 中\"\"\"\n",
    "    eval_question = np.load('../data/eval_question.npy')\n",
    "    with open('../data/sr_topic2id.pkl', 'rb') as inp:\n",
    "        sr_topic2id = pickle.load(inp)\n",
    "        sr_id2topic = pickle.load(inp)\n",
    "    pred_labels = np.asarray(predict_labels_list).reshape([-1])\n",
    "    pred_topics = sr_id2topic[pred_labels].values.reshape([-1, 5])   # 转为 topic\n",
    "    df_result = pd.DataFrame({'question':eval_question, 'tid0': pred_topics[:,0], 'tid1':pred_topics[:, 1],\n",
    "                         'tid2': pred_topics[:,2], 'tid3':pred_topics[:,3],'tid4': pred_topics[:,4]})\n",
    "    df_result.to_csv(result_path, index=False, header=False)\n",
    "    print('Finished writing the result')\n",
    "    return df_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 1699/1699 [01:49<00:00, 13.34it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min 45s, sys: 13.3 s, total: 1min 58s\n",
      "Wall time: 1min 52s\n",
      "Finished writing the result\n",
      "('len(df_result)=', 217360)\n",
      "Saving the predict_scores into ../scores/ch3-2-cnn-256-23457.npy\n",
      "('predict_scores.shape=', (217360, 1999))\n",
      "Finished saving the result!\n"
     ]
    }
   ],
   "source": [
    "%time predict_labels_list,predict_scores = predict()\n",
    "df_result = write_result(predict_labels_list, result_path=result_path) \n",
    "print('len(df_result)=',len(df_result))  # 结果应该为 217360\n",
    "print('Saving the predict_scores into %s' % scores_path)\n",
    "print('predict_scores.shape=',predict_scores.shape)\n",
    "np.save(scores_path, predict_scores)\n",
    "print('Finished saving the result!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>tid0</th>\n",
       "      <th>tid1</th>\n",
       "      <th>tid2</th>\n",
       "      <th>tid3</th>\n",
       "      <th>tid4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6215603645409872328</td>\n",
       "      <td>-6839713564940654454</td>\n",
       "      <td>4610596224687453206</td>\n",
       "      <td>-7506384235581390893</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-6306904715218704629</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6649324930261961840</td>\n",
       "      <td>2858911571784840089</td>\n",
       "      <td>3418451812342379591</td>\n",
       "      <td>-240041917918953337</td>\n",
       "      <td>-212983527176510806</td>\n",
       "      <td>2382911985227044227</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-4251899610700378615</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "      <td>-429636223750539488</td>\n",
       "      <td>-8955755936847898358</td>\n",
       "      <td>-7358589937244777363</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6213817087034420233</td>\n",
       "      <td>5804619920623030604</td>\n",
       "      <td>-8655945395761165989</td>\n",
       "      <td>-4966205278807386328</td>\n",
       "      <td>-3966324279534387421</td>\n",
       "      <td>244937959911721367</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-8930652370334418373</td>\n",
       "      <td>3972493657017129406</td>\n",
       "      <td>-8963554618409314978</td>\n",
       "      <td>-6925670792665757873</td>\n",
       "      <td>-1115593437686158905</td>\n",
       "      <td>6018641953300645757</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               question                  tid0                  tid1  \\\n",
       "0   6215603645409872328  -6839713564940654454   4610596224687453206   \n",
       "1   6649324930261961840   2858911571784840089   3418451812342379591   \n",
       "2  -4251899610700378615   2919247920214845195  -5265476641576484497   \n",
       "3   6213817087034420233   5804619920623030604  -8655945395761165989   \n",
       "4  -8930652370334418373   3972493657017129406  -8963554618409314978   \n",
       "\n",
       "                   tid2                  tid3                  tid4  \n",
       "0  -7506384235581390893   2919247920214845195  -6306904715218704629  \n",
       "1   -240041917918953337   -212983527176510806   2382911985227044227  \n",
       "2   -429636223750539488  -8955755936847898358  -7358589937244777363  \n",
       "3  -4966205278807386328  -3966324279534387421    244937959911721367  \n",
       "4  -6925670792665757873  -1115593437686158905   6018641953300645757  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_result.head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>tid0</th>\n",
       "      <th>tid1</th>\n",
       "      <th>tid2</th>\n",
       "      <th>tid3</th>\n",
       "      <th>tid4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6215603645409872328</td>\n",
       "      <td>4610596224687453206</td>\n",
       "      <td>-6839713564940654454</td>\n",
       "      <td>-6306904715218704629</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-8091907016971478715</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6649324930261961840</td>\n",
       "      <td>3418451812342379591</td>\n",
       "      <td>2858911571784840089</td>\n",
       "      <td>2382911985227044227</td>\n",
       "      <td>-240041917918953337</td>\n",
       "      <td>3383016985780045156</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-4251899610700378615</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-7358589937244777363</td>\n",
       "      <td>2816249700493135244</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "      <td>-3315241959305847628</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6213817087034420233</td>\n",
       "      <td>-8655945395761165989</td>\n",
       "      <td>5804619920623030604</td>\n",
       "      <td>-4966205278807386328</td>\n",
       "      <td>7476760589625268543</td>\n",
       "      <td>-2523521411748733187</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-8930652370334418373</td>\n",
       "      <td>3972493657017129406</td>\n",
       "      <td>-8963554618409314978</td>\n",
       "      <td>-1115593437686158905</td>\n",
       "      <td>1870872991887862017</td>\n",
       "      <td>6018641953300645757</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               question                  tid0                  tid1  \\\n",
       "0   6215603645409872328   4610596224687453206  -6839713564940654454   \n",
       "1   6649324930261961840   3418451812342379591   2858911571784840089   \n",
       "2  -4251899610700378615   2919247920214845195  -7358589937244777363   \n",
       "3   6213817087034420233  -8655945395761165989   5804619920623030604   \n",
       "4  -8930652370334418373   3972493657017129406  -8963554618409314978   \n",
       "\n",
       "                   tid2                  tid3                  tid4  \n",
       "0  -6306904715218704629   2919247920214845195  -8091907016971478715  \n",
       "1   2382911985227044227   -240041917918953337   3383016985780045156  \n",
       "2   2816249700493135244  -5265476641576484497  -3315241959305847628  \n",
       "3  -4966205278807386328   7476760589625268543  -2523521411748733187  \n",
       "4  -1115593437686158905   1870872991887862017   6018641953300645757  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 参考结果\n",
    "df_result.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在全部预测正确的情况下，理论值为：f1=0.713933\n",
    "precision=2.50273, recall=0.998873, f1=0.713933"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在全部预测正确的情况下，理论值为：\n",
      "precision=2.50273, recall=0.998873, f1=0.713933\n"
     ]
    }
   ],
   "source": [
    "# 假设全部正确，f1 值最高能到多少\n",
    "def padding_label(labels):\n",
    "    \"\"\"把所有的label补齐到长度为 5\"\"\"\n",
    "    label_len = len(labels)\n",
    "    if label_len >= 5:\n",
    "        return labels[:5]\n",
    "    return np.hstack([labels, np.zeros(5-label_len, dtype=int) - 1])\n",
    "    \n",
    "\n",
    "marked_labels_list = data_valid.y.tolist() # 所有的标注结果\n",
    "predict_labels_list = map(padding_label, marked_labels_list)\n",
    "predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "print '在全部预测正确的情况下，理论值为：'\n",
    "print 'precision=%g, recall=%g, f1=%g' % (precision, recall, f1)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [conda root]",
   "language": "python",
   "name": "conda-root-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
